<template>
  <div class="tiny-list h-full">
    <n-card class="h-full shadow-sm rounded-16px">
      <template #header>
        <n-space :size="[0, 0]" justify="space-between">
          <n-button size="small" type="primary" @click="openGetModal">
            <icon-fluent:save-copy-24-filled class="mr-5px" />
            获取对账单
          </n-button>
          <!-- <n-space class="text-10px w-600px h-28px overflow-auto">{{ tableDomIds }}</n-space> -->
          <n-space>
            <n-form :model="filterModel" inline :show-label="false" :show-feedback="false">
              <n-form-item label="对账单种类" path="billClass">
                <n-select
                  v-model:value="filterModel.billClass"
                  :options="billClassOptions"
                  size="small"
                  class="w-120px"
                />
              </n-form-item>
              <n-form-item label="对账单类型" path="billType">
                <n-select
                  v-model:value="filterModel.billType"
                  :options="billTypeOptions"
                  size="small"
                  class="w-120px"
                />
              </n-form-item>
              <n-form-item label="日期范围" path="dateRange">
                <shortcuts-rangdata v-model:value="filterModel.dateRange" class="w-260px" />
              </n-form-item>
              <n-form-item>
                <n-button size="small" type="primary" @click="getDataSource">
                  <icon-tabler:search class="mr-5px" />
                  查询
                </n-button>
              </n-form-item>
            </n-form>
          </n-space>
        </n-space>
      </template>
      <template #default>
        <loading-empty-wrapper class="h-full" :loading="loading" :empty="empty">
          <n-data-table
            ref="tableDom"
            :data="rowData"
            :row-key="rowKey"
            :columns="columnsRef"
            :pagination="pagination"
            :bordered="false"
            :single-line="false"
            :row-props="rowProps"
            :scroll-x="1650"
            :row-class-name="rowClassName"
            virtual-scroll
            flex-height
            size="small"
            class="h-full"
            striped
            @update-sorter="handleSorterChange"
            @update-page="getTableData"
            @update-page-size="getTableData"
          />
        </loading-empty-wrapper>
      </template>
    </n-card>
    <ul class="more-data">
      <li v-for="(item, index) in totalData" :key="index">
        <span>{{ item.name }}:</span>
        <span>{{ item.val }}</span>
      </li>
    </ul>
    <edit-modal v-model:visible="editVisible" />
    <get-statement-modal v-model:visible="getVisible" />
  </div>
</template>

<script setup lang="tsx">
import { onMounted, nextTick, ref, reactive, computed, watch, onUnmounted } from 'vue';
import { NText } from 'naive-ui';
import type { DataTableColumn, PaginationProps, DataTableSortState } from 'naive-ui';
import { useDateFormat } from '@vueuse/core';
import { fetchPurchaseList } from '@/service';
import { useBillContext } from '@/context';
import { useLoadingEmpty, useBoolean } from '@/hooks';
import EditModal from './components/edit-modal/index.vue';
import GetStatementModal from './components/GetStatement.vue';
import shortcutsRangdata from './components/ShortcutsRangdata.vue';

// 配置上下文
const { useProvide } = useBillContext();
const { billNo, newBill, tableData, setBillNo, setNewBill, setBillStatus, setTableData } = useProvide();

// 配置对账单种类选项
const billClassOptions = ref([
  {
    label: '采购对账单',
    value: '1'
  },
  {
    label: '委外对账单',
    value: '2'
  }
]);

// 配置对账单类型选项
const billTypeOptions = ref([
  {
    label: '全部对账单',
    value: '0'
  },
  {
    label: '售前对账单',
    value: '1'
  },
  {
    label: '售后对账单',
    value: '2'
  }
]);

// 初始加载、模态窗口状态
const { loading, startLoading, endLoading, empty } = useLoadingEmpty();
const { bool: editVisible, setTrue: openEditModal } = useBoolean();
const { bool: getVisible, setTrue: openGetModal } = useBoolean();

// 配置分页参数
const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 20,
  pageSlot: 7,
  showSizePicker: true,
  showQuickJumper: true,
  size: 'small',
  pageSizes: [10, 20, 50, 100, 200, 500],
  suffix({ itemCount }) {
    return `共${itemCount}条记录`;
  },
  onChange: (page: number) => {
    pagination.page = page;
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
  }
});

// 配置表格列参数
const pager: any = pagination;
const pageItemTotal = computed(() => (pager.page - 1) * pager.pageSize);
const columns: DataTableColumn[] = [
  {
    title: '序号',
    key: 'serial',
    width: 50,
    align: 'center',
    fixed: 'left',
    render(_, index) {
      return `${index + 1 + pageItemTotal.value}`;
    }
  },
  {
    key: 'A.BILL_DATE',
    title: '单据日期',
    width: 100,
    sortOrder: false,
    sorter: 'default'
  },
  {
    key: 'A.BILL_NO',
    title: '单据编号',
    width: 180,
    sortOrder: false,
    sorter: 'default',
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'A_DEPTID.DEPT_NAME',
    title: '部门名称',
    width: 160,
    sortOrder: false,
    sorter: 'default',
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'A_OBJID.CUST_NAME',
    title: '供应商名称',
    sortOrder: false,
    sorter: 'default',
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'A.JS_AMOUNT',
    title: '结算金额',
    width: 100,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.JSKK_AMOUNT1',
    title: '损耗扣款金额',
    width: 120,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.JSKK_AMOUNT2',
    title: '促销扣款金额',
    width: 120,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.JSKK_AMOUNT3',
    title: '调整金额',
    width: 100,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.KP_AMOUNT',
    title: '应开票金额',
    width: 120,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.KK_AMOUNT',
    title: '其他扣款金额',
    width: 120,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.AP_AMOUNT',
    title: '应付金额',
    width: 100,
    sortOrder: false,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.CONFIRM_PERSION_ID',
    title: '审核状态',
    width: 80,
    align: 'center',
    fixed: 'right',
    sortOrder: false,
    sorter: 'default',
    render: (row: any) => {
      if (row['A.CONFIRM_PERSION_ID'] !== null) {
        const textTypes: any = {
          0: 'warning',
          1: 'success',
          2: 'primary'
        };
        const textNames: any = {
          0: '未审核',
          1: '已审核',
          2: '待审核'
        };
        return <NText type={textTypes[row['A.CONFIRM_PERSION_ID']]}>{textNames[row['A.CONFIRM_PERSION_ID']]}</NText>;
      }
      return '';
    }
  },
  {
    key: 'A.TJ_STATUS',
    title: '处理状态',
    width: 80,
    align: 'center',
    fixed: 'right',
    sortOrder: false,
    sorter: 'default',
    render: (row: any) => {
      if (row['A.TJ_STATUS'] !== null) {
        const textTypes: any = {
          0: 'warning',
          1: 'primary',
          2: 'error',
          3: 'success'
        };
        const textNames: any = {
          0: '未提交',
          1: '已提交',
          2: '已退回',
          3: '受理通过'
        };
        return <NText type={textTypes[row['A.TJ_STATUS']]}>{textNames[row['A.TJ_STATUS']]}</NText>;
      }
      return '';
    }
  }
];
const columnsRef = ref(columns);

// 受控的排序
function handleSorterChange(sorter: DataTableSortState) {
  getDataSource();
  columnsRef.value.forEach((column: any) => {
    if (column.sortOrder === undefined) return;
    if (!sorter) {
      column.sortOrder = false;
      return;
    }
    if (column.key === sorter.columnKey) column.sortOrder = sorter.order;
    else column.sortOrder = false;
  });
}

// 初始排序
// handleSorterChange({
//   columnKey: 'A.BILL_DATE', // 单据日期
//   order: 'ascend', // 从远到近，如不排序值为 false
//   sorter: 'default'
// });

// 配置查询参数
const now = new Date();
const cur = now.getTime();
const nowDay = now.getDate() - 1;
const filterModel = ref({
  billClass: '1',
  billType: '0',
  dateRange: [cur - nowDay * 24 * 60 * 60 * 1000, cur] as const // 本月1日到今天
});

// 处理获取的数据
const rowData = ref<any>([]);
const totalData = ref<any>([]);
function setDataSource(data: any) {
  const { rows, total } = data;
  rowData.value = rows;
  totalData.value = total;
}

// 获取接口数据并处理加载状态
async function getDataSource() {
  const { billClass, billType, dateRange } = filterModel.value;
  if (dateRange) {
    const beginDate = useDateFormat(dateRange[0], 'YYYY/MM/DD').value;
    const endDate = useDateFormat(dateRange[1], 'YYYY/MM/DD').value;
    const options = ref({
      billClass,
      billType,
      beginDate,
      endDate
    });
    startLoading();
    const { data } = await fetchPurchaseList(options.value);
    if (data) {
      setDataSource(data);
      endLoading();
      getTableData();
      columnsRef.value = columns;
    } else {
      rowData.value = [];
      columnsRef.value = [];
      endLoading();
    }
  } else {
    window.$message?.error(`请选择日期范围`);
  }
}

// 获取表格渲染后的数据
const tableDom: any = ref(null);
const tableDomIds: any = ref([]);
function getTableData() {
  nextTick(() => {
    if (tableDom.value) {
      tableDomIds.value = tableDom.value.paginatedData.map((item: any) => [
        item.rawNode['A.BILL_NO'],
        item.rawNode['A.TJ_STATUS']
      ]);
      setTableData({
        pageData: tableDomIds.value,
        pageSize: pagination.pageSize,
        pageIndex: pagination.page,
        arrSize: rowData.value.length
      });
    }
  });
}

// 双击表格行进入编辑弹窗
const rowKey = (row: any) => row.BILL_ID;
function rowProps(row: any) {
  return {
    style: '',
    ondblclick: () => {
      setNewBill(false);
      setBillStatus(row['A.TJ_STATUS']);
      handleEdit(row['A.BILL_NO']);
    }
  };
}
function handleEdit(bn: any) {
  setBillNo(bn);
  openEditModal();
}

// 处理表格需要标记的行
const rowClassName = (row: any) => {
  const color: any = row.COLOR;
  if (color) {
    if (color === 1) {
      return 'text-red';
    }
    if (color === 2) {
      return 'bg-yellow';
    }
    if (color === 3) {
      return 'text-red bg-yellow';
    }
  }
  return '';
};

// 监听是否为新对账单，然后打开编辑窗口
const openEdit = watch(
  () => billNo.value,
  newNo => {
    if (newBill.value) {
      handleEdit(newNo);
    }
  }
);

// 监听是否翻页
const setPage = watch(
  () => tableData.value.pageIndex,
  newPage => {
    pagination.page = newPage;
    getTableData();
  }
);

// 销毁监听
onUnmounted(() => {
  openEdit();
  setPage();
});

// 初始化加载数据
onMounted(() => {
  getDataSource();
});
</script>

<style scoped>
.more-data {
  font-size: 12px;
  line-height: 100%;
  position: absolute;
  display: flex;
  align-items: center;
  width: calc(100% - 560px);
  height: 45px;
  left: 25px;
  bottom: 10px;
}
.more-data li {
  float: left;
  vertical-align: middle;
  margin-right: 15px;
}
.more-data li span {
  display: inline-block;
  white-space: nowrap;
}
.more-data li span:first-child {
  margin-right: 5px;
}
:deep(.text-red td) {
  color: rgb(255, 0, 0) !important;
}

:deep(.bg-yellow td) {
  background-color: rgb(255, 255, 210) !important;
}

html.dark div:deep(.bg-yellow td) {
  background-color: rgb(73, 67, 49) !important;
}
</style>
